package drds.global_transaction.resource_manager.undolog.undo_executor;

import drds.common.ShouldNeverHappenException;
import drds.global_transaction.resource_manager.model.Column;
import drds.global_transaction.resource_manager.model.Image;
import drds.global_transaction.resource_manager.model.KeyType;
import drds.global_transaction.resource_manager.model.Record;
import drds.global_transaction.resource_manager.undolog.UndoLog;

import java.util.List;

public class DeleteUndoExecutor extends UndoExecutor
{

	public DeleteUndoExecutor(UndoLog undoLog)
	{
		super(undoLog);
	}

	@Override
	protected String buildUndoSql()
	{
		Image beforeImage = undoLog.getBeforeImage();
		List<Record> beforeImageRecordList = beforeImage.getRecordList();
		if (beforeImageRecordList == null || beforeImageRecordList.size() == 0)
		{
			throw new ShouldNeverHappenException("invalid undo log");
		}
		Record record = beforeImageRecordList.get(0);
		StringBuilder insertColumnNames = new StringBuilder();
		StringBuilder insertColumnValues = new StringBuilder();
		Column primaryKeyColumn = null;
		boolean first = true;
		for (Column column : record.getColumnList())
		{
			if (column.getKeyType() == KeyType.primary_key)
			{
				primaryKeyColumn = column;
				continue;
			} else
			{
				if (first)
				{
					first = false;
				} else
				{
					insertColumnNames.append(", ");
					insertColumnValues.append(", ");
				}
				insertColumnNames.append(column.getName());
				insertColumnValues.append("?");
			}

		}
		if (first)
		{
			first = false;
		} else
		{
			insertColumnNames.append(", ");
			insertColumnValues.append(", ");
		}
		insertColumnNames.append(primaryKeyColumn.getName());
		insertColumnValues.append("?");

		return "insert into " + undoLog.getTableName() + "(" + insertColumnNames.toString() + ") values (" + insertColumnValues.toString() + ")";
	}

	@Override
	protected Image getUndoImage()
	{
		return undoLog.getBeforeImage();
	}
}
